<script lang="ts" setup>
import { Modal, message } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import type { T } from 'vitest/dist/reporters-yx5ZTtEV.js';
import type { UnwrapRef } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import ExcelJS from 'exceljs';
import { useDownExcel } from '../useDownExcel';
import { useUpload } from '../useUpload';
import details_add from './details_add.vue';

const router = useRouter();

const route = useRoute();

const data = ref<any[]>([]);

const loading = ref<boolean>(false);

const departmentName = ref<any>();

async function getData() {
  loading.value = true;
  await getAssessmentListByDepartment(departmentName.value).then((res: any) => {
    data.value = res.data;
  }).finally(() => {
    loading.value = false;
  });
}

// 合并单元格
function rowSpan(key: any) {
  const arr = data.value
    .reduce((result, item) => {
      if (!result.includes(item[key])) {
        result.push(item[key]);
      }
      return result;
    }, [])
    .reduce((result: any, keys: any) => {
      const children = data.value.filter(item => item[key] === keys);
      result = result.concat(children.map((item, index) => ({
        ...item,
        [`${key}RowSpan`]: index === 0 ? children.length : 0,
      })));
      return result;
    }, []);
  return arr;
}

// 表头
const columns: any[] = [
  {
    title: '类别',
    dataIndex: 'category',
    key: 'category',
    width: '8%',
    align: 'center',
    customRender: ({ text, record, index }: AAPI.RenderProps<T>) => {
      const data = rowSpan('category');
      record = data[index];
      return {
        children: text,
        props: {
          rowSpan: record.categoryRowSpan,
        },
      };
    },
  },
  {
    title: '考核项目',
    dataIndex: 'assessmentItem',
    key: 'assessmentItem',
    width: '10%',
    align: 'center',
    customRender: ({ text, record, index }: AAPI.RenderProps<T>) => {
      const data = rowSpan('assessmentItem');
      record = data[index];
      return {
        children: text,
        props: {
          rowSpan: record.assessmentItemRowSpan,
        },
      };
    },
  },
  {
    title: '权重',
    dataIndex: 'weight',
    key: 'weight',
    width: '5%',
    align: 'center',
  },
  {
    title: '目标值',
    dataIndex: 'target',
    key: 'target',
    width: '15%',
    align: 'center',
    customRender: ({ text, record, index }: AAPI.RenderProps<T>) => {
      const data = rowSpan('target');
      record = data[index];
      return {
        children: text,
        props: {
          rowSpan: record.targetRowSpan,
        },
      };
    },
  },
  {
    title: '计分方法',
    dataIndex: 'selfScoringMethod',
    key: 'selfScoringMethod',
    width: '20%',
    align: 'center',
    customRender: ({ text, record, index }: AAPI.RenderProps<T>) => {
      const data = rowSpan('selfScoringMethod');
      record = data[index];
      return {
        children: text,
        props: {
          rowSpan: record.selfScoringMethodRowSpan,
        },
      };
    },
  },
  {
    title: '备注',
    dataIndex: 'notes',
    key: 'notes',
    width: '10%',
    align: 'center',
  },
  {
    title: '目标值',
    dataIndex: 'targetValue',
    key: 'targetValue',
    width: '10%',
    align: 'center',
  },
  {
    title: '完成值',
    dataIndex: 'completionValue',
    key: 'completionValue',
    width: '10%',
    align: 'center',
  },
  {
    title: '完成率/排名',
    dataIndex: 'completionRateRank',
    key: 'completionRateRank',
    width: '7%',
    align: 'center',
  },
  {
    title: '得分',
    dataIndex: 'score',
    key: 'score',
    width: '5%',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'lastColumn',
    width: '10%',
    align: 'center',
    fixed: 'right',
  },
];

onMounted(() => {
  departmentName.value = route.query.departmentName;
  getData();
});

// 编辑和删除
const editableData: UnwrapRef<Record<string, any>> = reactive({});

function edit(id: number) {
  editableData[id] = cloneDeep(data?.value?.filter((item: any) => id === item.id)[0]);
}

async function save(id: number) {
  const newData = Object.assign(data?.value?.filter((item: any) => id === item.id)[0], editableData[id]);
  const updateDate = {
    id: newData.id,
    assessedDepartment: newData.assessedDepartment,
    category: newData.category,
    assessmentItem: newData.assessmentItem,
    weight: newData.weight,
    target: newData.target,
    selfScoringMethod: newData.selfScoringMethod,
    notes: newData.notes,
    targetValue: newData.targetValue,
    completionValue: newData.completionValue,
    completionRateRank: newData.completionRateRank,
    score: newData.score,
  };
  await updateAssessment(updateDate).then(() => {
    message.success('修改成功!');
    getData();
  });
  delete editableData[id];
}

function cancel(id: number) {
  delete editableData[id];
}

async function deleteData(id: number) {
  await deleteAssessmentById(id).then(() => {
    message.success('删除成功!');
  });
}

function onDelete(id: number) {
  Modal.confirm({
    title: () => '确定要删除吗？',
    okText: () => '是的',
    okType: 'danger',
    cancelText: () => '取消',
    onOk() {
      data.value = data.value.filter((item: any) => item.id !== id);
      // 删除逻辑
      deleteData(id);
    },
  });
}

// 添加
const visible = ref<boolean>(false);

function add() {
  getVisible();
}

function getVisible() {
  visible.value = !visible.value;
  getData();
}

// 返回
function back() {
  router.push('/assessment_indicators/kpi');
}

// excel文件上传
const fileList = ref<any>([]);

// 移除文件
function handleRemove(file: any) {
  const index = fileList.value.findIndex((f: { uid: any }) => f.uid === file.uid);
  fileList.value.splice(index, 1);
}

// 阻止自动上传
function beforeUpload(file: any) {
  fileList.value = [];
  fileList.value.push(file);
  return false; // 阻止自动上传
}

// 手动上传
async function handleManualUpload() {
  if (fileList.value.length === 0) {
    message.error('请上传文件！');
    return;
  }
  fileList.value.forEach(async (file: any) => {
    // 判断文件类型
    if (useUpload().checkIfExcel(file.name || '')) {
      // loading.value = true;
      const formData = new FormData();
      formData.append('file', file);
      const reader = new FileReader();
      reader.onload = async (e) => {
        const buffer: any = e.target?.result;
        if (buffer) {
          const workbook = new ExcelJS.Workbook();
          await workbook.xlsx.load(buffer).then(async () => {
            // 上传到数据库
            await addAssessmentFileupload(formData).then(() => {
              message.success('上传成功！');
              // 移除文件
              handleRemove(file);
              // 更新数据
              getData();
            })
              .catch(() => {
                message.error('上传失败');
                // 重新更新数据，将原先显示在页面的数据撤回
                getData();
              });
          });
        }
      };
      reader.readAsArrayBuffer(file);
    }
    else {
      message.error('请上传execl文件！');
    }
  });
}
</script>

<template>
  <PubPageMain class="max">
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            {{ departmentName }}
          </div>
          <a-button type="link" @click="add">
            添加考核项
          </a-button>
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <a-upload
            v-auth="'e-index-upload'" :file-list="fileList" :before-upload="beforeUpload" name="file"
            :multiple="false" action="" accept=".xlsx, .xls" :on-remove="handleRemove"
          >
            <a-button>
              <upload-outlined /> 点击选择文件
            </a-button>
          </a-upload>
          <a-button v-auth="'e-index-upload'" type="primary" @click="handleManualUpload">
            上传
          </a-button>
          <a-button type="primary" @click="useDownExcel().downMohthExcelByDepartment(departmentName)">
            导出为excel
          </a-button>
          <a-button v-auth="'a_i_exitquota'" type="primary" @click="back">
            返回
          </a-button>
        </a-space>
      </div>
    </div>
    <details_add
      v-if="visible" class="index-add" :visible="visible" :get-visible="getVisible"
      :department-name="departmentName"
    />
    <div class="content">
      <a-table
        :columns="columns" :data-source="data" :scroll="{ x: 2000 }" :pagination="false" :loading="loading"
        bordered class="d-table"
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex === 'operation'">
            <div class="editable-row-operations">
              <span v-if="editableData[record.id]">
                <a-typography-link @click="save(record.id)">保存</a-typography-link>
                <a @click="cancel(record.id)">取消</a>
              </span>
              <span v-else>
                <a-space>
                  <a @click="edit(record.id)">编辑</a>
                  <a v-if="data.length" @click="onDelete(record.id)">删除</a>
                </a-space>
              </span>
            </div>
          </template>
          <template v-else>
            <div>
              <a-input
                v-if="editableData[record.id]"
                v-model:value="editableData[record.id][column.dataIndex as string]" style="margin: -5px 0;"
              />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
        </template>
      </a-table>
    </div>
  </PubPageMain>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;
  overflow: auto;

  .header {
    position: sticky;
    top: 0;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    background-color: #fff;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .content {
    display: flex;
    flex: 1;
    flex-direction: column;
    width: 100%;
    height: 95%;
    overflow: auto;
    overflow-y: auto;

    .d-table {
      flex-grow: 1;
      height: 100%;
      max-height: 100%;
      padding: 10px;
    }
  }
}

.editable-row-operations a {
  margin-right: 8px;
}
</style>
